import random

import redis
from PIL import Image, ImageDraw, ImageFont
from LaboratoryBuilding.settings import REDIS_HOST, REDIS_PORT
from django.http import HttpResponse

# 建立连接
r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT)
def GraphCode():
    # 创建画布    mode  模式,"RGB"  size  画布的尺寸  定义图片对象
    image = Image.new("RGB", (200, 70), createcolor())
    # 定义画笔
    imageDraw = ImageDraw.Draw(image, "RGB")
    import io
    charsource = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"
    sum = ""
    for i in range(4):
        tmp_num = random.randrange(len(charsource))
        ch = charsource[tmp_num]
        imageDraw.text((15 + i * 50, 10), ch, fill=createcolor(),
                       font=ImageFont.truetype(font="C:/Windows/Fonts/Arial.ttf", size=50))
        # 这个字体是本机的位置里面的字体
        sum += ch
    # 创建一个字节流
    byteIO = io.BytesIO()
    # 把图片放在字节流里面     保存到缓冲区
    image.save(byteIO, "png")
    # 保存随机码
    # 这里的code需要替换一个随便变的key uid最好
    r.set("code", sum)
    print(r.get("code"))
    return HttpResponse(byteIO.getvalue(), "image/png")
    # 随机颜色的生成


def createcolor():
    red = random.randint(0, 255)
    green = random.randint(0, 255)
    blue = random.randint(0, 255)
    return (red, green, blue)